package conf

import (
	"gin_mall/dao"
	"strings"

	"gopkg.in/ini.v1"
)

var (
	AppMode  string
	HttpPort string

	Host        string
	ProductPath string
	AvatarPath  string

	Db         string
	DbHost     string
	DbPort     string
	DbUser     string
	DbPassword string
	DbName     string

	RedisDb       string
	RedisAddr     string
	RedisPassWord string
	RedisName     string

	ValidEmail string
	SmtpHost   string
	SmtpPort   int
	SmtpEmail  string
	SmtpPass   string

	EsHost  string
	EsPort  string
	EsIndex string
)

func Init() {
	file, err := ini.Load("./conf/config.ini")
	if err != nil {
		panic("读取配置文件失败:\n%s" + err.Error())
	}
	loadServer(file, "service")
	loadPath(file, "path")
	loadMysqlData(file, "mysql")
	loadRedisData(file, "redis")
	loadEmail(file, "email")
	loadEs(file, "es")
	// root:Hankex123@tcp(127.0.0.1:3306)/db_name?charset=utf8&parseTime=true
	pathRead := strings.Join([]string{DbUser, ":", DbPassword, "@tcp(", DbHost, ":", DbPort, ")/", DbName, "?charset=utf8&parseTime=true"}, "")
	pathWrite := strings.Join([]string{DbUser, ":", DbPassword, "@tcp(", DbHost, ":", DbPort, ")/", DbName, "?charset=utf8&parseTime=true"}, "")
	dao.DataBase(pathRead, pathWrite)
}

func loadServer(file *ini.File, serviceName string) {
	AppMode = file.Section(serviceName).Key("AppMode").String()
	HttpPort = file.Section(serviceName).Key("HttpPort").String()
}

func loadPath(file *ini.File, serviceName string) {
	Host = file.Section(serviceName).Key("Host").String()
	ProductPath = file.Section(serviceName).Key("ProductPath").String()
	AvatarPath = file.Section(serviceName).Key("AvatarPath").String()
}

func loadMysqlData(file *ini.File, serviceName string) {
	Db = file.Section(serviceName).Key("Db").String()
	DbHost = file.Section(serviceName).Key("DbHost").String()
	DbPort = file.Section(serviceName).Key("DbPort").String()
	DbUser = file.Section(serviceName).Key("DbUser").String()
	DbPassword = file.Section(serviceName).Key("DbPassword").String()
	DbName = file.Section(serviceName).Key("DbName").String()
}

func loadRedisData(file *ini.File, serviceName string) {
	RedisDb = file.Section(serviceName).Key("RedisDb").String()
	RedisAddr = file.Section(serviceName).Key("RedisAddr").String()
	RedisPassWord = file.Section(serviceName).Key("RedisPassWord").String()
	RedisName = file.Section(serviceName).Key("RedisName").String()
}

func loadEmail(file *ini.File, serviceName string) {
	ValidEmail = file.Section(serviceName).Key("ValidEmail").String()
	SmtpHost = file.Section(serviceName).Key("SmtpHost").String()
	SmtpPort = file.Section(serviceName).Key("SmtpPort").MustInt(465)
	SmtpEmail = file.Section(serviceName).Key("SmtpEmail").String()
	SmtpPass = file.Section(serviceName).Key("SmtpPass").String()
}

func loadEs(file *ini.File, serviceName string) {
	EsHost = file.Section(serviceName).Key("EsHost").String()
	EsPort = file.Section(serviceName).Key("EsHost").String()
	EsIndex = file.Section(serviceName).Key("EsHost").String()
}
